﻿/*
 * This file is part of MonoSettlers.
 *
 * Copyright (C) 2010-2011 Christoph Husse
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: 
 *      # Christoph Husse
 * 
 * Also checkout our homepage: http://opensettlers.codeplex.com/
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using OpenTK;
using OpenTK.Input;
using OpenTK.Graphics;
using System.Runtime.InteropServices;
using System.Threading;

#if EMBEDDED
    using OpenTK.Graphics.ES20;
#else
using OpenTK.Graphics.OpenGL;
#endif

namespace MonoSettlers.RenderSystem
{
    public partial class GLRenderer : IRenderSystem
    {
        private void OnRender()
        {
            CheckError();

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // setup render state for sprites
            GL.Enable(EnableCap.Texture2D);
            GL.DepthFunc(DepthFunction.Lequal);
            GL.Enable(EnableCap.DepthTest);

            // TODO: why does OpenGL need this to enable translucency if we are using a pixelshader anyway? I am confused...
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.Enable(EnableCap.Blend);

            CheckError();

            // just calculate the current Z-Values, but don't do any rendering!
            IsRenderPass = false;
            IsSelectionPass = false;
            {
                foreach (var visual in m_Visuals)
                {
                    visual.Render();
                }
            }

            var zOrderedVisuals = (from e in m_Visuals orderby e.ZValue ascending select e).ToArray();

            // obtain selection information
            m_SelectionPassResults.Clear();
            IsSelectionPass = true;
            IsRenderPass = true;
            {
                GL.ClearColor(Color.Black);
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                // setup GLSL program
                m_2DSceneSelectProgram.Bind(m_ProjMatrix, m_ViewMatrix, m_ModelMatrix);

                GL.ActiveTexture(TextureUnit.Texture0);

                if (m_2DSceneSelectProgram.Texture1Location.HasValue)
                    GL.Uniform1(m_2DSceneSelectProgram.Texture1Location.Value, 0);

                // selection pass (each one is rendered with an unique color)
                foreach (var visual in zOrderedVisuals)
                {
                    visual.Render();
                }

                // process selection information
                int[] selectedPixels = new int[1];
                int selValue;
                var prevMouseOver = MouseOverVisual;

                GL.ReadPixels(MouseXY.X, ViewportHeight - MouseXY.Y, 1, 1, PixelFormat.Rgb, PixelType.UnsignedByte, selectedPixels);

                if (selectedPixels[0] > 0)
                {
                    selValue = (selectedPixels[0] / SelectionGranularity) - 1;

                    if ((selValue >= 0) && (selValue < m_SelectionPassResults.Count))
                        MouseOverVisual = m_SelectionPassResults[selValue];
                    else
                        MouseOverVisual = null;
                }
                else
                    MouseOverVisual = null;

                if (prevMouseOver != MouseOverVisual)
                {
                    // raise selection events
                    var newOver = MouseOverVisual;

                    ThreadPool.QueueUserWorkItem((unused) =>
                    {
                        var mouseLeave = OnMouseLeave;
                        var mouseEnter = OnMouseEnter;

                        if ((mouseLeave != null) && (prevMouseOver != null))
                            mouseLeave(this, prevMouseOver);

                        if ((mouseEnter != null) && (newOver != null))
                            mouseEnter(this, newOver);
                    });
                }
            }


            // now comes the final part, rendering the 2D scene...
            IsRenderPass = true;
            IsSelectionPass = false;
            {
                GL.ClearColor(Color.DarkGreen);

                // setup GLSL program
                m_2DSceneProgram.Bind(m_ProjMatrix, m_ViewMatrix, m_ModelMatrix);

                GL.ActiveTexture(TextureUnit.Texture0);

                if (m_2DSceneProgram.Texture1Location.HasValue)
                    GL.Uniform1(m_2DSceneProgram.Texture1Location.Value, 0);

                // render pass
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                foreach (var visual in zOrderedVisuals)
                {
                    visual.Render();
                }
            }

            // render level points
            GL.Clear(ClearBufferMask.DepthBufferBit);

            if (IsBuildingGridVisible)
            {
                int selectionIndex = 0;

                for (int y = 0; y < VisualsPerScreenLine; y++)
                {
                    for (int x = 0; x < VisualsPerScreenLine; x++)
                    {
                        const double w = 0.4, s = (1 - w) / 2;

                        selectionIndex += 0x010101;

                        if (m_BuildingGrid[x, y] < 0)
                            continue;

                        m_BuildingGridTextures[Math.Min(m_BuildingGridTextures.Length - 1, m_BuildingGrid[x, y])].Bind();

                        DrawSprite(null, x + s, y + s, w, w);
                    }
                }
            }
        }
    }
}
